# 10.4 存储数据
# 10.4.1 使用json.dump() 和json.load()
import json

# 函数json.dump() 接受两个实参：要存储的数据以及可用于存储数据的文件对象。
numbers = [1, 3, 5, 7, 9]
filename = 'numbers.json'
with open(filename, 'w') as f_obj:
    json.dump(numbers, f_obj)

filename = 'numbers.json'
with open(filename) as f_obj:
    numbers2 = json.load(f_obj)
print(numbers2)

# 10.4.2 保存和读取用户生成的数据
filename = 'username1.json'
try:
    with open(filename) as f_obj:
        username = json.load(f_obj)
except FileNotFoundError:
    username = input("你叫什么名字？")
    with open(filename, 'w') as f_obj:
        json.dump(username, f_obj)
        print("我们将记住您的名字，", username)
else:
    print("欢迎回来," + username)


# 10.4.3 重构
def greet_user():
    filename2 = 'username2.json'
    try:
        with open(filename2) as f_obj1:
            username1 = json.load(f_obj1)
    except FileNotFoundError:
        username1 = input("你叫什么名字？")
        with open(filename2, 'w') as f_obj1:
            json.dump(username1, f_obj1)
            print("我们将记住您的名字，", username1)
    else:
        print("欢迎回来," + username1)


greet_user()
